#include "apue.h"
#include <assert.h>
void t0_handler(int signo)
{
    printf("收到了【%d】号信号\n", signo);
}

void t0()
{
    /*
        测试SIGPIPE信号
        当向已经关闭读端的管道写入时，会收到SIGPIPE信号

        [现象]
        运行此函数，10秒后会不断收到13号信号。
    */
    signal(SIGPIPE, t0_handler);
    int pipefd[2] = {0};
    int n = pipe(pipefd);
    assert(n != -1);
    pid_t pid = fork();
    if (pid == 0)
    {
        close(pipefd[1]);
        // 10秒后关闭读端
        sleep(10);
        close(pipefd[0]);
        while (1)
            ;
    }
    close(pipefd[0]);
    while (1)
    {
        const char *str = "Hello";
        write(pipefd[1], str, sizeof(str));
        sleep(1);
    }
}

static void
sig_usr(int signo)
{
    if (signo == SIGUSR1)
        printf("received SIGUSR1\n");
    else if (signo == SIGUSR2)
        printf("received SIGUSR2\n");
    else
        err_dump("received signal %d\n", signo);
}

void t1()
{
    if (signal(SIGUSR1, sig_usr) == SIG_ERR)
        err_sys("can’t catch SIGUSR1");
    if (signal(SIGUSR2, sig_usr) == SIG_ERR)
        err_sys("can’t catch SIGUSR2");
    if (signal(2, sig_usr) == SIG_ERR)
        err_sys("can’t catch SIGINT");
    for (;;)
        pause();
}

int main()
{
    t1();
    return 0;
}